#include "game.hpp"
#include "snake.hpp"

#include <SFML/Graphics.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/Window.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/WindowStyle.hpp>

#define NORESIZE 2
#define HEIGH 800
#define WIDTH 600
#define BLOCK_SIZE 20
#define PADDING 5
#define SPEED 0.35
#define BG_COLORR 62
#define BG_COLORG 62
#define BG_COLORB 68

int main() {
  sf::RenderWindow window(sf::VideoMode(HEIGH, WIDTH), "Snake",
                          sf::Style::Default ^ NORESIZE);

  Game my_game(HEIGH, WIDTH, BLOCK_SIZE, PADDING);
  Snake my_snake(my_game);

  sf::Clock clock;
  my_game.new_food(4818);
  unsigned short direction = 0;

  while (window.isOpen()) {

    sf::Event event;

    while (window.pollEvent(event)) {

      switch (event.type) {
      case sf::Event::Closed:
        window.close();
        break;

      case sf::Event::KeyPressed:
        switch (event.key.code) {
        case sf::Keyboard::Left:
          direction = 1;
          break;
        case sf::Keyboard::Up:
          direction = 2;
          break;
        case sf::Keyboard::Right:
          direction = 3;
          break;
        case sf::Keyboard::Down:
          direction = 4;
          break;
        default:
          break;
        }

      default:
        break;
      }
    }
    window.clear(sf::Color(BG_COLORR, BG_COLORG, BG_COLORB));

    // Check is it time to move
    sf::Time elapsed_time = clock.getElapsedTime();
    if (elapsed_time.asSeconds() >= SPEED) {
      my_snake.set_direction(direction);
      my_snake.cycle();
      clock.restart();
    }
    auto &myField = my_game.getField();
    for (auto el : my_snake.get_history()) {
      auto rect = (sf::RectangleShape(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE)));
      auto [x, y] = myField[el];
      rect.setPosition(x, y);
      window.draw(rect);
    }
    auto rect = (sf::RectangleShape(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE)));
    auto [x, y] = myField[my_game.get_food_cord()];
    rect.setPosition(x, y);
    rect.setFillColor(sf::Color::Green);
    window.draw(rect);

    window.display();
  }
  return 0;
}
